<template>
  <div class="tree-list">
    <el-cascader
      ref="elcascader"
      v-model="modelVal"
      :options="options"
      :props="{
        multiple: false,
        checkStrictly: true,
        emitPath: false,
        expandTrigger: 'hover',
      }"
      :placeholder="placeholder"
      clearable
      filterable
    >
    </el-cascader>
  </div>
</template>
<script>
export default {
  name: "category-select",
  model: {
    prop: "level",
    event: "change",
  },
  props: {
    // v-model绑定的值
    level: {
      type: [String, Array],
      default: "",
    },
    isOther: {
      type: Boolean,
      default: false,
    },
    isroot: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请选择分类",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 可选最大等级，可以用来区分新增修改和选择产品分类
    // 给产品绑定分类时可以传入4，新增修改时选择父品类时需要小于4
    maxLevel: {
      type: Number,
      default: 3,
    },
  },
  watch: {
    level: {
      handler(n, o) {
        this.modelVal = n;
      },
      immediate: true,
    },
    modelVal(n) {
      this.$emit("change", n);
      setTimeout(() => {
        let node = this.$refs.elcascader.getCheckedNodes();
        this.$emit("levelChange", node[0]?.level);
      }, 0);
    },
    "$attrs.areaCode": {
      handler(n) {
        this.getData();
      },
    },
  },
  data() {
    return {
      options: [],
      modelVal: "",
      props: {},
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.$POST(
        "sot-admin-api/product/front-category/queryFrontCategoryTree",
        {
          parentId: "0",
          needCloudProduct: "0",
          areaCode: this.$attrs.areaCode,
        }
      ).then((res) => {
        if (res.errorCode === "00000") {
          if (this.isroot) {
            res.data = [
              {
                id: "0",
                label: "顶级节点",
                parentId: "-1",
                title: "顶级节点",
                children: res.data,
              },
            ];
          }

          this.processingData(res.data, 1); //处理数据

          if (this.isOther) {
            res.data.push({
              value: "-1",
              label: "其他",
              parentId: "-1",
              title: "其他",
            });
          }

          this.options = res.data;
        }
      });
    },
    processingData(data, level) {
      data.forEach((item) => {
        item.value = item.id;
        if (level < this.maxLevel) {
          if (item.children !== null) {
            this.processingData(item.children, level + 1);
          }
        } else {
          item.children = null;
        }
      });
    },
  },
};
</script>
